﻿using Message;
using UnityEngine;
using UnityEngine.UI;

public class LoginPanel : PanelBase
{
    private InputField uname;
    private InputField pwd;

    private Button loginBtn;
    private Button backBtn;

    public override void Init(params object[] args)
    {
        base.Init(args);
        layer = PanelLayer.Panel;
    }

    public override void OnShowing()
    {
        base.OnShowing();
        Transform skinTrans = panelObj.transform;
        loginBtn = skinTrans.Find("loginBtn").GetComponent<Button>();
        backBtn = skinTrans.Find("backBtn").GetComponent<Button>();
        uname = skinTrans.Find("uname").GetComponent<InputField>();
        pwd = skinTrans.Find("pwd").GetComponent<InputField>();

        loginBtn.onClick.AddListener(OnLogin);
        backBtn.onClick.AddListener(OnBack);

    }

    private void OnLogin()
    {
        //连接服务器
        if (NetMgr.Instance.status != NetMgr.Status.Connected)
        {
            MsgMgr.Instance.AddListener("ConnectBack", OnConnectBack);
            NetMgr.Instance.Connect();
            return;
        }
        else
        {
            Login();
        }
    }

    void OnConnectBack(object[] args)
    {
        bool state = (bool)args[0];
        if (state)
        {
            Login();
        }
        else
        {
            Loom.QueueOnMainThread(() =>
            {
                PanelMgr.Instance.OpenPanel<TipPanel>("", "连接服务器失败!");
                //NetMgr.Instance.Close();
            });
        }
    }

    private void OnBack()
    {
        Close();
        PanelMgr.Instance.OpenPanel<RegisterPanel>("");
    }

    void Login()
    {
        //注册登录返回结果回调
        MsgMgr.Instance.AddListener(typeof(SToCLoginRet).ToString(), OnLoginBack);

        //发送
        CToSLogin protocol = new CToSLogin();
        protocol.uname = uname.text;
        protocol.pwd = Util.GetStringHash(pwd.text);
        NetMgr.Instance.Send(protocol);
    }

    private void OnLoginBack(object[] args)
    {
        Loom.QueueOnMainThread(() =>
        {


            //移除登录返回结果回调
            MsgMgr.Instance.RemoveListener(typeof(SToCLoginRet).ToString(), OnLoginBack);

            SToCLoginRet stcl = args[0] as SToCLoginRet;
            if (stcl.code == 0)
            {
                Debug.Log("uid:" + stcl.uid);
                GlobeData.uid = stcl.uid;
                GlobeData.uname = uname.text;
                PanelMgr.Instance.OpenPanel<TipPanel>("TipPanel", "登录成功!");
                PanelMgr.Instance.OpenPanel<MainPanel>("MainPanel");
                Close();
            }
            else
            {
                PanelMgr.Instance.OpenPanel<TipPanel>("TipPanel", "登录失败!");
            }
        });
    }

}
